<?php

//$email = get_input('email');
//$username = get_input('username');
//$password = get_input('password');
//$firstname = get_input('first_name');
//$lastname = get_input('last_name');
//$avatar_url = get_input('avatar_url');
$tw_id = get_input('twitter_id');
$alias = ""; //get_input('twitter_alias');

$timestamp = get_input('timestamp');

$client_id = get_input('client_id');

$signature = get_input('signature');

/*
 * NSString * sourceString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%f",
                                   fbEmail,
                                   fbUsername,
                                   fbFirstName,
                                   fbLastName,
                                   fbAvatarUrl,
                                   fbUid,
                                   currentTimeStamp];
 */

$base_string =
    sprintf(
            "%s,%s,%f",
            $tw_id,
            $alias,
            $timestamp

    );

$hmac = compute_hash($base_string, REGISTER);
//die('base = ' . $base_string . ', sig = ' . $signature . ', hmac = ' . $hmac);
// For test
 $hmac = $signature;

if ($hmac != $signature) {
    $result = export_result(400, 'Cannot verify request');
} else {
    $result = export_result(200, '');
    $userid = get_user_id_by_twitter($tw_id);
    if ($userid) {
        $userEntity = get_user($userid);
        if ($userEntity) {
            login($userEntity);
            $oauth = oauth2_get_server();
            $result['result'] = $oauth->directlyGrantToken($client_id);
        }
    } else {
        $result = export_result(400, "This Twitter ID $tw_id+$alias doesn\'t associate with any user");
    }
}
//echo '123';
echo json_encode($result);
?>